﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using Newtonsoft.Json;
using Copad.BusinessCard.Model;
using System.Web.SessionState;
using System.IO;
using System.Xml.Serialization;
using System.Web.UI;
using Copad.BusinessCard.BLL;

/// <summary>
///Manager 的摘要说明
/// </summary>
public class Manager
{
    private static string imagePath = null;
    private static string remarkImagePath = null;
    private static string invalidParametersJsonText = JsonConvert.SerializeObject(new JsonResult { Result = false, Message = "传递的参数不正确！" });
    private static string accessDeniedJsonText = JsonConvert.SerializeObject(new { Result = false, Message = "未授权访问！" });
    private static string databaseFailureJsonText = JsonConvert.SerializeObject(new { Result = false, Message = "操作数据库出错，请重试或联系管理员！" });
    private static UserInfo currentUser;
    private static string rootPath;
    private static SystemSet config;
    private static WorkTimeManager workTime;

    public const string SYSTEM_NAME = "系统管理员";

    static Manager()
    {
        //imagePath = ConfigurationManager.AppSettings["ImageRootPath"].Replace("{AppDir}", HttpRuntime.AppDomainAppPath);
        //rootPath = HttpContext.Current.Server.MapPath("~/");

    }

    public static string InvalidParametersJsonText { get { return invalidParametersJsonText; } }
    public static string AccessDeniedJsonText { get { return accessDeniedJsonText; } }
    public static string DatabaseFailureJsonText { get { return databaseFailureJsonText; } }
    public static string ImageRootPath { get { return imagePath; } }
    public static string RemarkImageRootPath { get { return remarkImagePath; } }
    public static UserInfo CurrentUser { get { return currentUser; } }
    public static string RootPath { get { return rootPath; } }
    public static SystemSet Configure { get { return config; } }
    public static WorkTimeManager TimeManager { get { return workTime; } }
    public static readonly LogBLL Loger = new LogBLL();

    public static void Init()
    {
        rootPath = System.Web.Hosting.HostingEnvironment.MapPath("~/");
        Manager.imagePath = ConfigurationManager.AppSettings["ImageRootPath"].Replace("{AppDir}", HttpRuntime.AppDomainAppPath);
        Manager.remarkImagePath = ConfigurationManager.AppSettings["RemarkImageRootPath"].Replace("{AppDir}", HttpRuntime.AppDomainAppPath);
        try
        {
            config = LoadConfig<SystemSet>(rootPath + "\\System.config");
        }
        catch (Exception ex)
        {
            //throw;
            config = new SystemSet();
        }

        try
        {
            workTime = LoadConfig<WorkTimeManager>(RootPath + "\\work.config");
        }
        catch (Exception ex)
        {
            //throw;
            workTime = WorkTimeManager.GetDefault();
        }
    }

    public static void SetLogined(UserInfo user, HttpSessionState session)
    {
        currentUser = user;
        session["userInfo"] = user;
        session["loginPassword"] = user.User.Password;
        //rootPath = HttpContext.Current.Server.MapPath("~/");
    }

    public static bool IsSystemUser()
    {
        return currentUser.Groups.Where(w => w.Name == SYSTEM_NAME).FirstOrDefault() != null;
    }

    public static void SaveConfig<T>(T obj, string filePath)
    {
        Stream stream = null;
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            stream = new FileStream(filePath, FileMode.Create);
            serializer.Serialize(stream, obj);
        }
        finally
        {
            if (stream != null) { stream.Close(); }
        }
    }

    public static T LoadConfig<T>(string filePath)
    {
        Stream stream = null;
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            stream = new FileStream(filePath, FileMode.OpenOrCreate);
            return (T)serializer.Deserialize(stream);
        }
        finally
        {
            if (stream != null) { stream.Close(); }
        }
    }

    public static string GetFileExtName(string filename)
    {
        FileInfo fileInfo = new FileInfo(filename);
        return fileInfo.Extension;
    }

    public static void SaveTimeManager()
    {
        Manager.SaveConfig<WorkTimeManager>(workTime, Manager.RootPath + "\\work.config");
    }

    public static void SaveSystemSet()
    {
        Manager.SaveConfig<SystemSet>(config, Manager.RootPath + "\\SystemSet.config");
    }

    public static void ShowMessage(ITextControl control, string message, Exception ex = null)
    {
        string text = message;

        if (config.IsDebug && ex != null)
        {
            text += "<br/>" + ex.Message;
        }
        control.Text = text;
        if (control is Control)
        {
            ((Control)control).Visible = true;
        }
    }

    public static void WriteLog(OperationEnum operation, string content)
    {
        if (content.Length > 1024)
        {
            content = content.Substring(0, 1015) + "...【超长截断】";
        }
        try
        {
            Loger.Insert(new Log { LogTime = DateTime.Now, Operation = operation, Content = content, IP = HttpContext.Current.Request.UserHostAddress });
        }
        catch (Exception ex)
        {
            //
        }
    }

    public static void WriteLog(string content)
    {
        WriteLog(OperationEnum.Other, content);
    }

    public static void WriteLog(OperationEnum operation, Exception ex)
    {
        WriteLog(operation, "操作异常：<br/>" + ex.Message + "<br/>" + ex.StackTrace);
    }

    public static void WriteLog( Exception ex)
    {
        WriteLog(OperationEnum.Exception, ex);
    }
}